<?php

namespace Miniapp\Controllers;

class LoginController extends AuthController {

    public function MinibegLoginAction() {
        $encryptedData = $_POST['encryptedData'] ? $_POST['encryptedData'] : E("加密信息不能为空");
        $rawData = $_POST['rawData'] ? $_POST['rawData'] : E("用户信息不能为空");
        $iv = $_POST['iv'] ? $_POST['iv'] : E("iv不能为空");
        $code = $_POST['code'] ? $_POST['code'] : E("code不能为空");
        $wechatService = service("Wechat/WechatService");
        $sessionKey = $wechatService->getMiniappSessionKey($code);
        if ($sessionKey == false) {
            E("登录失败");
        }
        $openId = $sessionKey['openid'];
        $unionId = $sessionKey['unionid'];
        $sessionKey = $sessionKey['sessionKey'];
        if (empty($unionId)) {
            $encryptedData = $wechatService->getMiniappEncryptData($sessionKey, $encryptedData, $iv);
            $unionId = $encryptedData["unionid"];
        }
        $userService = service("User/UserService");
        $user = $userService->OpenIdLogin($openId, 1);
        if ($user == false) {
            $rawData = json_decode($rawData, true);
            $user = $userService->register($openId, 1, $unionId, $rawData['nickName'], $rawData['avatarUrl'], $rawData['city'], $rawData['province'], $rawData['country'], $rawData['gender'] == 0 ? $rawData['gender'] = 1 : $rawData['gender']);
        }
        $user['userId'] = lib("Encrypt")->encrypt($user['id']);
        $user['openId'] = $openId;
        unset($user['id']);
        unset($user['unionId']);
        $this->renderJson($user);
    }

}
